using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.DirectoryServices;

using GonzalesCore.CoreElements;
using GonzalesCore.CoreManagers;

using Kypris2.CoreElements;

using Jamila2.Tools;

public partial class _Default : System.Web.UI.Page
{
    #region Variables

    #region RedirectPath
    protected string RedirectPath
    {
        get
        {
            return ViewState["RedirectPath"].ToString();
        }

        set
        {
            ViewState["RedirectPath"] = value;
        }
    }
    #endregion

    #region Active Directory Specific

    protected string JobTitle = "";
    protected string DirectManagerID = "";
    protected string ADDistingushedName = "";
    protected string Department = "";
    protected string Email = "";

    #endregion

    #region InternalID

    public string InternalID
    {
        get
        {
            return ViewState["InternalID"].ToString();
        }

        set
        {
            ViewState["InternalID"] = value;
        }
    }

    #endregion

    #region MessageByLanguage

    protected string MessageProfileError
    {
        get
        {
            return ViewState["MessageProfileError"].ToString();
        }

        set
        {
            ViewState["MessageProfileError"] = value;
        }
    }

    protected string MessageLoginError
    {
        get
        {
            return ViewState["MessageLoginError"].ToString();
        }

        set
        {
            ViewState["MessageLoginError"] = value;
        }
    }

    protected string MessageADFailed
    {
        get
        {
            return ViewState["MessageADFailed"].ToString();
        }

        set
        {
            ViewState["MessageADFailed"] = value;
        }
    }

    #endregion

    #endregion

    #region Event Actions

    #region Page_Load
    protected void Page_Load(object sender, EventArgs e)
    {
        if (GonzalesGeneralVariables.MaintenanceMode && !GonzalesGeneralVariables.GhostMode)
        {
            Response.Redirect(GonzalesInformationPageRedirect.ServerMaintainance);
        }

        if (!IsPostBack)
        {
            #region Active Directory
            if (Request.QueryString["ad"] != null)
            {
                this.TextBox_LoginID.Text = Request.QueryString["ad"];
            }
            #endregion

            #region Redirect Path
            if (Request.QueryString["redirect"] != null)
            {
                this.RedirectPath = Request.QueryString["redirect"];
            }
            else
            {
                this.RedirectPath = "";
            }
            #endregion

            #region Internal ID

            if (Request.QueryString["id"] != null)
            {
                this.InternalID = Request.QueryString["id"];
            }

            #endregion

            if (this.RedirectPath.Length > 0)
            {
                this.StorePageRedirect();
            }

            this.Title = GonzalesSystemInformation.WebApplicationTitle;
            this.PageComponentSetup();
            this.SwitchLanguage();

            try
            {
                if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    this.TextBox_LoginID.Text = System.Web.HttpContext.Current.User.Identity.Name.Substring(System.Web.HttpContext.Current.User.Identity.Name.LastIndexOf("\\"));
                }
            }
            catch (Exception)
            {
                // do nothing
            }
        }

    }
    #endregion

    #region Button_Login_Click
    protected void Button_Login_Click(object sender, EventArgs e)
    {

        if (GonzalesGeneralVariables.GhostMode)
        {
            // login using Ghost Mode
            // only highest authority can login without password
            PrivateLoginSession TmpSession = new PrivateLoginSession((new SystemUser(this.TextBox_LoginID.Text, "First Login")), GonzalesGeneralVariables.DatabaseType, GonzalesGeneralVariables.DatabaseConnectionString);

            using (UserManager CurUserManager = new UserManager(TmpSession))
            {
                SystemUser CurrentLoginUser = CurUserManager.GetUserByEmailID(this.TextBox_LoginID.Text, true);

                if (CurrentLoginUser != null)
                {
                    TmpSession.CurrentLoggedOnUser = CurrentLoginUser;
                    Session[GonzalesCommonNamingConvention.CurrentPrivateSession] = TmpSession;

                    Response.Redirect("index2.aspx");
                }
                else
                {
                    this.Label_Message.ForeColor = System.Drawing.Color.Red;
                    this.Label_Message.Text = this.MessageProfileError;
                }
            }

        }
        else if (GonzalesGeneralVariables.MaintenanceMode)
        {
            // go to maintenance page
            Response.Redirect(GonzalesInformationPageRedirect.ServerMaintainance);
        }
        else if (this.CheckBox_LoginOnBehalf.Checked)
        {
            // muz go thru AD first at least
            if (this.ActiveDirectoryLogin())
            {
                // if success, check if this login on behalf is valid
                PrivateLoginSession TmpSession = new PrivateLoginSession((new SystemUser(this.TextBox_LoginID.Text, "First Login")), GonzalesGeneralVariables.DatabaseType, GonzalesGeneralVariables.DatabaseConnectionString);

                using (UserManager CurUserManager = new UserManager(TmpSession))
                {
                    SystemUser CurrentOnBehalfOf = CurUserManager.GetUserByEmailID(this.TextBox_LoginOnBehalfID.Text, true);
                    SystemUser CurrentLoginUser = CurUserManager.GetUserByEmailID(this.TextBox_LoginID.Text, true);

                    if (CurrentOnBehalfOf != null && CurrentLoginUser != null)
                    {
                        /* Edited on by Victor, 3/21/2009 */
                        if ((CurrentOnBehalfOf.OnBehalfBy != null && CurrentOnBehalfOf.OnBehalfBy.InternalID.CompareTo(CurrentLoginUser.InternalID) == 0) ||
                            (CurrentOnBehalfOf.ReviewOnBehalfBy != null && CurrentOnBehalfOf.ReviewOnBehalfBy.InternalID.CompareTo(CurrentLoginUser.InternalID) == 0))
                        {
                            // on behalf success
                            TmpSession = new PrivateLoginSession(CurrentOnBehalfOf, CurrentLoginUser, GonzalesGeneralVariables.DatabaseType, GonzalesGeneralVariables.DatabaseConnectionString);
                            Session[GonzalesCommonNamingConvention.CurrentPrivateSession] = TmpSession;

                            Response.Redirect("index2.aspx");
                        }
                        else
                        {
                            // display error message, load user error
                            // this.Label_Message.Text = this.MessageProfileError;
                            this.Label_Message.ForeColor = System.Drawing.Color.Red;
                            this.Label_Message.Text = this.MessageLoginError;
                        }
                    }
                    else
                    {
                        // display error message, load user error
                        this.Label_Message.ForeColor = System.Drawing.Color.Red;
                        this.Label_Message.Text = this.MessageLoginError;
                        //this.Label_Message.Text = this.MessageProfileError;
                    }

                    if (CurrentLoginUser == null)
                    {
                        this.Label_Message.Text = this.MessageProfileError;
                        this.Label_Message.ForeColor = System.Drawing.Color.Red;
                    }

                }
            }
        }
        else
        {
            // normal login
            if (this.ActiveDirectoryLogin())
            {
                // successful login

                // temporaly account
                PrivateLoginSession TmpSession = new PrivateLoginSession((new SystemUser(this.TextBox_LoginID.Text, "First Login")), GonzalesGeneralVariables.DatabaseType, GonzalesGeneralVariables.DatabaseConnectionString);

                using (UserManager CurUserManager = new UserManager(TmpSession))
                {
                    SystemUser CurrentLoginUser = CurUserManager.GetUserByEmailID(this.TextBox_LoginID.Text, true);

                    if (CurrentLoginUser != null)
                    {
                        TmpSession.CurrentLoggedOnUser = CurrentLoginUser;
                        Session[GonzalesCommonNamingConvention.CurrentPrivateSession] = TmpSession;

                        //Commented by Agnes - For development purpose, to enable assistant mode
                        if (CurUserManager.UpdatePersonnelParticularUponLogin(
                            CurrentLoginUser.InternalID,
                            CurrentLoginUser.DisplayName.Replace("'", "''"),
                            this.JobTitle.Replace("'", "''"),
                            this.DirectManagerID.Replace("'","''"),
                            this.ADDistingushedName.Replace("'", "''"),
                            this.Department.Replace("'", "''"),
                            this.Email.Replace("'", "''")))
                        {
                            ((PrivateLoginSession)Session[GonzalesCommonNamingConvention.CurrentPrivateSession]).CurrentLoggedOnUser = CurUserManager.GetUserByEmailID(this.TextBox_LoginID.Text, true);

                            Response.Redirect("index2.aspx");
                        }
                        else
                        {
                            using (LogManager CurLogManager = new LogManager(TmpSession))
                            {
                                string LogID = SwissArmy.UniqueID();
                                CurLogManager.LogError(LogID, "[_Default.Button_Login_Click] : Failed at CurUserManager.UpdatePersonnelParticularUponLogin : " + CurUserManager.ErrorMessage, CurrentLoginUser, LogInterface.System);
                                this.Label_Message.Text = CurUserManager.ErrorMessage;
                            }
                        }
                    }
                    else
                    {
                        // display error message, load user error
                        this.Label_Message.ForeColor = System.Drawing.Color.Red;
                        this.Label_Message.Text = this.MessageProfileError;
                    }
                }

                //Response.Redirect("index2.aspx");
            }
            else
            {
                // active directory login failed
                //this.Label_Message.Text = this.MessageADFailed;
            }
        }
    }
    #endregion

    #region DropDownList_Language_SelectedIndexChanged
    protected void DropDownList_Language_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.SwitchLanguage();
    }
    #endregion

    #region CheckBox_LoginOnBehalf_CheckedChanged
    protected void CheckBox_LoginOnBehalf_CheckedChanged(object sender, EventArgs e)
    {
        this.Label_LoginOnBehalf.Visible = this.TextBox_LoginOnBehalfID.Visible = this.CheckBox_LoginOnBehalf.Checked;
    }
    #endregion

    #endregion

    #region Customized Methods

    #region PageComponentSetup
    protected void PageComponentSetup()
    {
        // title
        this.Title = GonzalesSystemInformation.WebApplicationTitle;

        // temporaly account
        PrivateLoginSession TmpSession = new PrivateLoginSession((new SystemUser("NIL", "First Login")), GonzalesGeneralVariables.DatabaseType, GonzalesGeneralVariables.DatabaseConnectionString);

        // language dropdown
        using (LanguageManager CurLanguageManager = new LanguageManager(TmpSession))
        {
            MasterBaseCollection ResultCollection = CurLanguageManager.GetAllLanguageInOrder(true);
            if (ResultCollection != null && ResultCollection.Count > 0)
            {
                this.DropDownList_Language.Items.Clear();

                for (int x = 0; x < ResultCollection.Count; x++)
                {
                    this.DropDownList_Language.Items.Add(new ListItem(ResultCollection[x].DisplayName, ResultCollection[x].InternalID));
                }
            }
        }

    }
    #endregion

    #region SwitchLanguage
    protected void SwitchLanguage()
    {
        MultiLingualFactory CurLanguageFactory = null;

        if (this.DropDownList_Language.Items.Count > 0)
        {
            CurLanguageFactory = MultiLingualEngine.GetMultiLingualFactory(this, this.DropDownList_Language.SelectedValue);
        }
        else
        {
            CurLanguageFactory = MultiLingualEngine.GetMultiLingualFactory(this, GonzalesGeneralVariables.DefaultLanguage);
        }

        using (CurLanguageFactory)
        {
            //this.Title = CurLanguageFactory.DisplayValue("Title");
            this.Label_FormTitle.Text = CurLanguageFactory.DisplayValue("SectionTitle");
            this.Label_LoginID.Text = CurLanguageFactory.DisplayValue("LoginID");
            this.Label_LoginPassword.Text = CurLanguageFactory.DisplayValue("Password");
            this.Label_Language.Text = CurLanguageFactory.DisplayValue("Language");
            this.Button_Login.Text = CurLanguageFactory.DisplayValue("ButtonLogin");
            this.Label_Instruction.Text = CurLanguageFactory.DisplayValue("Instruction");
            this.Label_Instruction2.Text = CurLanguageFactory.DisplayValue("Instruction2");
            this.Label_LoginOnBehalf.Text = CurLanguageFactory.DisplayValue("OnBehalfOf");
            this.CheckBox_LoginOnBehalf.Text = CurLanguageFactory.DisplayValue("LoginOnBehalfMode");

            this.MessageADFailed = CurLanguageFactory.DisplayValue("ADFailed");
            this.MessageProfileError = CurLanguageFactory.DisplayValue("ProfileError");
            this.MessageLoginError = CurLanguageFactory.DisplayValue("LoginError");
        }
    }
    #endregion

    #region ActiveDirectoryLogin
    public bool ActiveDirectoryLogin()
    {
        //return true;
        bool smooth = true;

        DirectoryEntry CurADSystem = null;
        DirectorySearcher CurADSearcher = null;
        SearchResult CurSearchResult = null;
        /*
        string[] ActiveDirectoryAddress = new string[2];
        ActiveDirectoryAddress[1] = GonzalesGeneralVariables.LDAP;
        ActiveDirectoryAddress[0] = GonzalesGeneralVariables.AlternateLDAP1;
        */

        string LDAP_Address = "";

        // temporaly account
        PrivateLoginSession TmpSession = new PrivateLoginSession((new SystemUser(this.TextBox_LoginID.Text, "First Login")), GonzalesGeneralVariables.DatabaseType, GonzalesGeneralVariables.DatabaseConnectionString);
        using (UserManager CurUserManager = new UserManager(TmpSession))
        {
            SystemUser LoginUser = CurUserManager.GetUserByEmailID(this.TextBox_LoginID.Text, true);
            if (LoginUser != null)
            {
                LDAP_Address = "LDAP://" + LoginUser.LDAP;
            }
        }

        if (LDAP_Address.Length > 0)
        {
            try
            {
                CurADSystem = new DirectoryEntry(LDAP_Address, this.TextBox_LoginID.Text, this.TextBox_Password.Text);
                CurADSearcher = new DirectorySearcher(CurADSystem);
                CurADSearcher.Filter = "samaccountname=" + this.TextBox_LoginID.Text;
                CurADSearcher.SearchScope = SearchScope.Subtree;
                CurSearchResult = CurADSearcher.FindOne();


                if (CurSearchResult != null)
                {
                    ResultPropertyCollection CurResultProperties = CurSearchResult.Properties;
                    foreach (string PropertyKey in CurResultProperties.PropertyNames)
                    {
                        switch (PropertyKey)
                        {
                            case "title":

                                foreach (Object TmpCollection in CurResultProperties[PropertyKey])
                                {
                                    this.JobTitle += TmpCollection.ToString();
                                }

                                break;

                            case "manager":

                                foreach (Object TmpCollection in CurResultProperties[PropertyKey])
                                {
                                    this.DirectManagerID += TmpCollection.ToString();
                                }
                                break;

                            case "distinguishedname":

                                foreach (Object TmpCollection in CurResultProperties[PropertyKey])
                                {
                                    this.ADDistingushedName += TmpCollection.ToString();
                                }
                                break;

                            case "mail":
                                foreach (Object TmpCollection in CurResultProperties[PropertyKey])
                                {
                                    this.Email += TmpCollection.ToString();
                                }
                                break;

                            case "department":
                                foreach (Object TmpCollection in CurResultProperties[PropertyKey])
                                {
                                    this.Department += TmpCollection.ToString();
                                }
                                break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // login failed                
                smooth = false;
                this.Label_Message.Text += ex.Message;
            }
            finally
            {
                // clean up
                CurADSystem.Close();
                CurADSystem.Dispose();

                CurADSearcher.Dispose();
                CurSearchResult = null;
            }
        }
        else
        {
            smooth = false;
            this.Label_Message.Text = "LDAP address is blank.";
        }



        return smooth;
    }
    #endregion

    #region Redirect

    protected void StorePageRedirect()
    {
        string page = "";

        switch (this.RedirectPath)
        {
            case "SUBMITTEDCLAIM":
                page = "GonzalesClaimsPendingForApprovalDetail.aspx?id=" + this.InternalID;
                break;

            case "APPROVEDCLAIM":
                page = "GonzalesMyClaimDetail.aspx?id=" + this.InternalID;
                break;

            case "ESCALATEDCLAIM":
                page = "GonzalesClaimsPendingForApprovalDetail.aspx?id=" + this.InternalID;
                break;

            case "PENDINGAUTHCLAIM":
                page = "GonzalesClaimsPendingForAuthorizedDetail.aspx?id=" + this.InternalID;
                break;

            case "REJECTEDCLAIM":
                page = "GonzalesMyClaimDetail.aspx?id=" + this.InternalID;
                break;

            case "REJECTEDNOTIFYAPPRCLAIM":
                page = "GonzalesViewClaim.aspx?id=" + this.InternalID;
                break;

            case "VERIFIEDCLAIM":
                page = "GonzalesClaimsPendingForVerificationDetail.aspx?id=" + this.InternalID;
                break;
        }

        Session[GonzalesCommonNamingConvention.CurrentRedirectSession] = page;
    }


    #endregion

    #endregion

}
